package com.macken.zjh.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.macken.zjh.Zjh;

public class Desktop {

	public int did;// 桌子编号
	public byte state;// 桌子状态
	// public Player[] players;
	public List<Player> players;
	public Map<Integer, Player> playerMap;// {pid:player}
	public Map<Byte, Player> playerPos;// {position:player}

	public int interval;

	public Desktop() {

	}

	public Desktop(int deskNum, byte deskState, int count, int[] ps,
			byte[] states, byte[] positions) {
		this.did = deskNum;
		this.state = deskState;
		players = new ArrayList<Player>();
		int pos = 0, i = 0;
		for (i = 0; i < count; i++) {
			Player p = new Player();
			p.pid = ps[i];
			p.state = states[i];
			p.serverPos = positions[i];
			if (p.pid == Zjh.pid) {
				pos = positions[i];
			}
			players.add(p);
		}
		playerMap = new HashMap<Integer, Player>();
		playerPos = new HashMap<Byte, Player>();
		interval = 3 - pos;
		for (i = 0; i < players.size(); i++) {
			Player p = players.get(i);
			p.clientPos = serverToClientPos(p.serverPos);
			playerMap.put(p.pid, p);
			playerPos.put(p.clientPos, p);
		}
	}

	public byte serverToClientPos(int serverPos) {
		int l = serverPos + interval;
		if (l > 5) {
			l = l - 5;
		} else if (l <= 0) {
			l = l + 5;
		}
		return (byte) l;
	}

	public void update(int did, byte state, int count, int[] pids,
			byte[] states, byte[] positions) {
		List<Player> plist = new ArrayList<Player>();
		this.did = did;
		this.state = state;
		for (int i = 0; i < count; i++) {
			Player p = playerMap.get(pids[i]);
			if (p != null) {
				p.state = states[i];
			} else {
				p = new Player();
				p.pid = pids[i];
				p.state = states[i];
				p.serverPos = positions[i];
				p.clientPos = serverToClientPos(p.serverPos);
				// playerMap.put(p.pid, p);
				// playerPos.put(p.clientPos, p);
			}
			plist.add(p);
		}
		Map<Integer, Player> pmap = new HashMap<Integer, Player>(5);
		Map<Byte, Player> ppos = new HashMap<Byte, Player>(5);
		for (int i = 0; i < plist.size(); i++) {
			Player p = plist.get(i);
			pmap.put(p.pid, p);
			ppos.put(p.clientPos, p);
		}
		//清除之前用户cookie
		for(int i=0;i<players.size();i++){
			Player p=players.get(i);
			if(pmap.get(p.pid)==null){
				p.dispose();
			}
		}
		players = plist;
		playerMap = pmap;
		playerPos = ppos;
		

	}

}
